package demo1;

import java.util.Arrays;

class Student implements Comparable<Student>{
    @Override
    public int compareTo(Student o) {
//        if(this.age>o.age){
//            return 1;
//        }else if(this.age==o.age){
//            return 0;
//        }else{
//            return -1;
//        }
//        return this.age-o.age;//这里的代码相当于上面的代码
        return this.name.compareTo(o.name);
    }//<里面写比较的类型>
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "demo1.Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class Test {

    public static void main(String[] args) {
        Student []students=new Student[3];
        students[0]=new Student("zhangsan",0);
        students[1]=new Student("lisi",20);
        students[2]=new Student("wang",23);

        System.out.println("排序前"+Arrays.toString(students));

        NameComparator nameComparator=new NameComparator();
        Arrays.sort(students,nameComparator);
        System.out.println("name排序后"+Arrays.toString(students));

        AgeComparator ageComparator=new AgeComparator();
        Arrays.sort(students,ageComparator);
        System.out.println("age排序后"+Arrays.toString(students));

        Arrays.sort(students);
        System.out.println("排序后"+Arrays.toString(students));
    }
    public static void mySort(Comparable[]comparables){
        //为什么要用接口?
        //模拟冒泡排序,自己实现arrays.sort
        for(int i=0;i<comparables.length-1;i++){
            for(int j=0;j<comparables.length-1-i;j++){
                if(comparables[j].compareTo(comparables[j+1])>0){
                    Comparable tmp=comparables[j];
                    comparables[j]=comparables[j+1];
                    comparables[j+1]=tmp;
                }
            }
        }
    }


    public static void main3(String[] args) {
        Student []students=new Student[3];
        students[0]=new Student("zhangsan",2);
        students[1]=new Student("lisi",2);
        students[2]=new Student("wang",2);

        System.out.println("排序前"+Arrays.toString(students));

        mySort(students);

        System.out.println("排序后"+Arrays.toString(students));
    }
    public static void main1(String[] args) {
        Student student1=new Student("张三",20);
        Student student2=new Student("李四",10);

//        System.out.println(student1<student2);
        System.out.println(student1.compareTo(student2));//谁调用了compareTo谁就是this
    }
}
